import { t } from 'i18next'
import React, { useEffect, useMemo, useRef, useState } from 'react'
import {
	CloseIcon,
	PanelStyle,
	RoomIcon,
	StyledFindVirtualRoomWrap,
	TipIcon,
	TipPopUpOptionStyled,
	TipPopUpStyled,
	DownIcon,
} from './style'
import useInit from '@/hooks/useInit'
import WebRecommendBrowser from '@/components/WebRecommendBrowser'
import { Button, Progress, Trigger, TriggerInstance, RadioGroup, CheckBox } from '@kedacom/react-next'
import ConfDurationModal from './ConfDurationModal'
import { useRequest } from 'ahooks'
import { fetchLoadVirtualResource } from '@/api/sysConfig/virtualRoomConfig'
import { fetchGetVirtualRooms } from '@/api/findVirtualRoom'
import Alert from '@/components/Alert'
import { IVirtualRooms } from '@/api/findVirtualRoom/interface'
import MeetingHeader from '@/components/MeetingHeader'
import { useGlobalStore } from '@/store/global'
import ShareModal from '@/components/ShareModal'
import { useStore } from '@/components/ShareModal/store'
import { IRoomConfigInfo } from '@/api/sysConfig/virtualRoomConfig/interface'
import VirtualRoomDetailModal from './VirtualRoomDetailModal'
import { useSize } from '@kedacom/hooks'
import shallow from 'zustand/shallow'
import { getScrollbarSize } from '@/utils'

const App = () => {
	/*
	isConfModalShow
	点击立即召开按钮，出现的弹窗是否出现 
	*/
	const [isConfModalShow, setIsConfModalShow] = useState(false)
	/*
	isDetailModalShow
	虚拟会议室详情 弹窗是否出现
	*/
	const [isDetailModalShow, setIsDetailModalShow] = useState(false)
	const [isShowTip, setIsShowTip] = useState(false)
	const [isShowList, setIsShowList] = useState(true)
	const [isCollapse, setIsCollapse] = useState(true)
	/*
	rooms
	虚拟会议室列表数据
	*/
	const [rooms, setRooms] = useState<IVirtualRooms[]>([])
	/*
	虚拟会议室总资源占用
	百分比
	*/
	const [percent, setPercent] = useState(0)
	/*
	sourceData 虚拟会议室总资源 percent数据
	虚拟会议室列表接口数据保存
	*/
	const [sourceData, setSourceData] = useState<IRoomConfigInfo[]>([])
	/*
	curData  当前操作的会议详情数据
	1. 点击名称，出现虚拟会议室详情
	*/
	const [curData, setCurData] = useState<IVirtualRooms | null>(null)
	const triggerRef = useRef<TriggerInstance>(null)
	const triggerOptionsRef = useRef<TriggerInstance>(null)
	const wrapRef = useRef(null)
	const wrapSize = useSize(wrapRef)
	/*
	chooseOption 选择搜索条件数据
	*/
	const [chooseOption, setChooseOption] = useState<{ type: Array<number>; modal: 0 | 1 }>({
		type: [1], //会议室类型
		modal: 0, // 显示模式 0 平铺 1 列表
	})
	/*
	虚拟会议室列表中
	每个item占用的宽度 动态设置

	wrapSize  内容区的宽度
	*/
	const roomWidth = useMemo(() => {
		if (!wrapSize?.width) {
			return 351
		} else {
			let paddingSpace = 31
			let allWidth = wrapSize.width + paddingSpace - (getScrollbarSize() ?? 10)
			let roomNumber = Math.floor(allWidth / 351)
			return Math.floor(allWidth / roomNumber) - 31
		}
	}, [wrapSize])

	const { user, SWITCH } = useGlobalStore((state) => ({ user: state.user, SWITCH: state.SWITCH }), shallow)
	const update = useStore((state) => state.update)
	useInit()
	/*
	接口请求 虚拟会议室总资源
	*/
	const { run: runLoadResource } = useRequest(() => fetchLoadVirtualResource(), {
		onSuccess: (res) => {
			if (res.success) {
				setSourceData(res.list)
				//设置总使用量进度条
				let totalAll = 0,
					totalUsed = 0
				res.list.forEach((item) => {
					totalAll += item.config_count
					totalUsed += item.config_used_count
				})
				setPercent(Math.floor((totalUsed / totalAll) * 100))
			} else {
				Alert(res.description || '')
			}
		},
	})
	/*
	接口请求 虚拟会议室列表数据
	*/
	const { run: runVirtualRooms } = useRequest(() => fetchGetVirtualRooms(), {
		onSuccess: (res) => {
			if (res.success) {
				setRooms(res.virtual_meeting_rooms ?? [])
			} else {
				Alert(res.description || '')
			}
		},
	})
	const handlerChoose = () => {
		triggerOptionsRef.current?.close()
		if (chooseOption.type.length === 0) {
			setIsShowList(false)
			setIsShowTip(false)
		} else {
			runVirtualRooms()
			setIsShowList(true)
			if (chooseOption.modal === 1) {
				runLoadResource()
				setIsShowTip(true)
				setIsCollapse(false)
			} else {
				setIsCollapse(true)
				setIsShowTip(false)
			}
		}
	}
	/*
	虚拟会议室总资源  progress 后面的 tipIcon的提示内容
	<Trigger ref={triggerRef} popup={TipPopUpPanel} popupPlacement="bottomEnd">
		<TipIcon />
	</Trigger>
	*/
	const TipPopUpPanel = (
		<TipPopUpStyled>
			{sourceData.map((source) => {
				let surplusCount = source.config_count - source.config_used_count
				let allCount = source.config_count
				return (
					<div className="source" key={source.id}>
						<Progress
							percent={(surplusCount / allCount) * 100}
							type="circle"
							showInfo={true}
							radius={30}
							strokeWidth={3}
							strokeColor={'#5eb9ef'}
							format={(percent) => <span className="text">{Math.ceil(percent)}%</span>}
						/>
						<div className="source-info">
							<div className="name">{source.name}</div>
							<div className="surplus-count">
								{t('剩余')}
								<span>{surplusCount}</span>
							</div>
							<div className="all-count">
								{t('总数')}
								{allCount}
							</div>
						</div>
					</div>
				)
			})}
			{/* 
			关闭弹窗
			*/}
			<CloseIcon className="close-btn" onClick={() => triggerRef.current?.close()} />
		</TipPopUpStyled>
	)
	/*
	TipPopUpOption 显示选择  
	出现的搜索条件弹窗
	*/
	const TipPopUpOption = (
		<TipPopUpOptionStyled>
			<div className="chooseOption">
				<div className="line">
					<div className="label">{t('会议室类型')}</div>
					<div className="checkbox">
						<CheckBox
							height={26}
							className="checked-item"
							onChange={(e, v) => {
								setChooseOption({ ...chooseOption, type: v ? [1] : [] })
							}}
							checked={chooseOption.type.length > 0}
						>
							{t('全部')}
						</CheckBox>
						<CheckBox
							className="checked-item"
							height={26}
							onChange={(e, v) => {
								setChooseOption({ ...chooseOption, type: v ? [1] : [] })
							}}
							checked={chooseOption.type.length > 0}
						>
							{t('192方')}
						</CheckBox>
					</div>
				</div>
				<div className="line">
					<div className="label">{t('显示模式')}</div>
					<RadioGroup
						value={chooseOption.modal}
						options={[
							{ label: t('平铺显示'), value: 0, height: 26, width: 122 },
							{ label: t('列表显示'), value: 1, height: 26, width: 122 },
						]}
						onChange={(e, v) => {
							setChooseOption({ ...chooseOption, modal: v })
						}}
					/>
				</div>
				<Button
					className="btn"
					onClick={() => {
						handlerChoose()
					}}
					width={80}
				>
					{t('筛选')}
				</Button>
			</div>
			<CloseIcon className="close-btn" onClick={() => triggerOptionsRef.current?.close()} />
		</TipPopUpOptionStyled>
	)
	/*
	handleShare  点击分享按钮
	*/
	const handleShare = (item: IVirtualRooms) => {
		update({
			meetingInfo: {
				name: item.name,
				meetingMoid: item.e164,
				e164: item.e164,
			},
			type: 'virtual',
			open: true,
		})
	}
	useEffect(() => {}, [chooseOption])
	return (
		<>
			{/* 
			WebRecommendBrowser 非谷歌浏览器弹窗提示 
			*/}
			<WebRecommendBrowser />
			<MeetingHeader tabIndex={3} />
			<StyledFindVirtualRoomWrap ref={wrapRef}>
				{rooms.length !== 0 ? (
					<div className="content">
						<div className="source-progress">
							<div className="label">{t('虚拟会议室总资源')}</div>
							<Progress
								className="progress"
								percent={percent}
								strokeColor="#7b9cce"
								width="195px"
								showInfo={true}
								format={(percent) => <span>{percent}%</span>}
							/>
							<Trigger ref={triggerRef} popup={TipPopUpPanel} popupPlacement="bottomEnd">
								<TipIcon />
							</Trigger>
							<Trigger ref={triggerOptionsRef} popup={TipPopUpOption} popupPlacement="bottomEnd">
								<Button className="showChange">
									<span>{t('显示选择')}</span>
									<DownIcon />
								</Button>
							</Trigger>
						</div>
						{isShowTip && (
							<div className="tips" onClick={() => setIsCollapse(!isCollapse)}>
								<PanelStyle isCollapse={isCollapse}></PanelStyle>
								<span>{t('192方')}</span>
								<span>
									{rooms.length}/{sourceData[0].config_count}
								</span>
							</div>
						)}
						<div className={`${isShowTip ? 'long' : ''} card-wrap`}>
							{isShowList &&
								isCollapse &&
								rooms.map((room) => (
									<div className="room-card" key={room.id} style={{ width: roomWidth }}>
										<div className="icon">
											<RoomIcon />
										</div>
										<div className="info">
											<div className="name-wrap">
												<span
													className="name"
													title={room.name}
													onClick={() => {
														setIsDetailModalShow(true)
														setCurData(room)
													}}
												>
													{room.exclusive === 1 ? `[vip]${room.name}` : room.name}
												</span>
												{!!SWITCH.share && (
													<span
														className="share-btn"
														title={t('分享')}
														onClick={() => handleShare(room)}
													>
														{t('分享')}
													</span>
												)}
											</div>
											<div className="type-wrap">
												<span className="label">{t('空闲 ')}</span>
												<span>{t('{{num}}方', { num: room.max_join_mt })}</span>
											</div>
											<div className="number-wrap">
												<span className="label">{t('虚拟会议室号码 ')}</span>
												<span>{room.e164}</span>
											</div>
											{/* <Button>显示选择</Button> */}
											{(user?.enable_cms_approval === 1 || user?.cms_virtual_approval === 0) && (
												<Button
													className="start-btn"
													onClick={() => {
														setIsConfModalShow(true)
														setCurData(room)
													}}
												>
													{t('立即召开')}
												</Button>
											)}
										</div>
									</div>
								))}
						</div>
						<ShareModal />
						{/* 
						点击立即召开按钮,出现的弹窗
						*/}
						<ConfDurationModal isShow={isConfModalShow} setIsShow={setIsConfModalShow} data={curData} />
						{/* 
						点击名称，出现虚拟会议室详情弹窗
						*/}
						<VirtualRoomDetailModal
							isShow={isDetailModalShow}
							setIsShow={setIsDetailModalShow}
							moid={curData?.id ?? ''}
							onStart={() => {
								setIsConfModalShow(true)
							}}
						/>
					</div>
				) : (
					<div className="empty">{t('当前无可用的虚拟会议室')}</div>
				)}
				<div className="footer"></div>
			</StyledFindVirtualRoomWrap>
		</>
	)
}
export default App
